<template>
    <van-nav-bar title="菜单分类" left-text="返回" left-arrow @click-left="onClickLeft" />
    <van-tree-select v-model:active-id="rightactiveval" 
    v-model:main-active-index="leftactiveIndex"
        :items="categoryData">

        <!--右侧显示图片-->
        <template #content>
            <van-grid :column-num="3" icon-size="50px">
                <van-grid-item v-for="value in categoryData[leftactiveIndex]?.children" :key="value.id" :icon="value.img" :text="value.text" :to="{ name: 'products', query: { categoryId: value.id}}"/>
            </van-grid>
        </template>

    </van-tree-select>

</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { CategoryApi } from '../../api';
const onClickLeft = () => history.back();
//右边选中项
const rightactiveval = ref(1);
//左边选中项索引
const leftactiveIndex = ref(0);
const categoryData2 = ref([
    { id: 1, name: "手机数码", img: "", parentId: 0 },
     {id:2, name:"华为手机",img:"",parentId:1},
    { id: 3, name: "小米手机", img: "", parentId: 1 },
    { id: 4, name: "智能家居", img: "", parentId: 0 },
    { id: 5, name: "炒菜机器人", img: "", parentId:4 },
    { id: 6, name: "智能水箱", img: "", parentId: 4 },

])

const categoryData = ref([
    {
        text: '浙江',
        children: [
            { text: '杭州', id: 1, img:'https://m.360buyimg.com/babel/jfs/t1/51031/14/17648/10793/6386f8fcEa5576b6f/19f261d5e5e7074b.png'},
            { text: '温州', id: 2 ,img:'https://m.360buyimg.com/babel/jfs/t1/51031/14/17648/10793/6386f8fcEa5576b6f/19f261d5e5e7074b.png'},
            { text: '宁波', id: 3, disabled: true },
        ],
    },
])
onMounted(() => {
    CallcategoryApi()
    categoryData2.value.forEach((item:any) => {
        item.text = item.name
    })
    console.log(categoryData2.value);
    //高阶函数进行分类
    let categoryData3 = categoryData2.value.reduce((newArray: any, currentValue: any) => {
        currentValue.children = categoryData2.value.filter((item: any) => {
            return item.parentId === currentValue.id
        })
        if (currentValue.parentId === 0) { 
            newArray.push(currentValue)
        }
        return newArray;
    }, [])
    categoryData.value = categoryData3;
})

//调用后台api接口
const CallcategoryApi = () => { 
    CategoryApi.select.call().then((res:any) => {
        res.forEach((item: any) => {
            item.text = item.name
        })
        //高阶函数进行分类
        let categoryData2 = res.reduce((newArray: any, currentValue: any) => {
            currentValue.children = res.filter((item: any) => {
                return item.parentId === currentValue.id
            })
            if (currentValue.parentId === 0) {
                newArray.push(currentValue)
            }
            return newArray;
        }, [])
        categoryData.value = categoryData2;
    })
}


</script>

<style scoped>

</style>